/**
 * 元素权限控制，绑定系统权限
 */
import React, { Component } from 'react';
import connectFn from '@/utils/connectFn';
import { StateType } from '@/common-typings';

interface WithElementAuthProps {
  btns?: string[];
  auth?: string | boolean;
}

const WithElementAuth = (ComposedComponent: typeof React.Component) => {
  class WithElementAuths extends Component<WithElementAuthProps> {
    // props中的关键字
    filterKey = ['auth', 'dispatch'];

    // 过滤props中的关键字，防止与原生标签属性重名等问题
    filterProps = (props: StateType) => {
      const result = {};
      Object.keys(props).forEach(key => {
        if (!this.filterKey.includes(key)) {
          result[key] = props[key];
        }
      });
      return result;
    };

    render() {
      const { btns, auth = false } = this.props;
      const newProps = this.filterProps(this.props);
      if (
        auth.toString() === 'true' ||
        (btns && btns.length && auth && btns.includes(auth.toString()))
      ) {
        return <ComposedComponent {...newProps} />;
      }
      return null;
    }
  }
  return connectFn([{ global: ['btns'] }])(WithElementAuths);
};

export default WithElementAuth;
